package com.guodu.util;

import java.util.Vector;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import com.guodu.entity.UserInfo;
import com.guodu.util.FileLocator;

public class UserSessionBindingListener implements HttpSessionBindingListener{

	private ServletContext application = null;

	public UserSessionBindingListener() {

	}

	public UserSessionBindingListener(ServletContext application) {
		super();
		if (application == null)
			throw new IllegalArgumentException(
					"Null application is not accept.");
		this.application = application;

	}

	public void valueBound(HttpSessionBindingEvent e) {

		try {
			Vector activeSessions = (Vector) application
					.getAttribute("activeSessions");
			if (activeSessions == null) {
				activeSessions = new Vector();
			}
			UserInfo sessionUser = (UserInfo) e.getSession().getAttribute("admin");
			if (sessionUser != null) {
				activeSessions.add(e.getSession());
			}
			application.setAttribute("activeSessions", activeSessions);
			FileLocator.synchFile(e.getSession().getId(), sessionUser
					.getUserId(), e.getSession().getCreationTime(), 1);
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
		}

	}

	public void valueUnbound(HttpSessionBindingEvent e) {

		try {
			FileLocator.synchFile(e.getSession().getId(), null, 0, 2);

			Vector activeSessions = (Vector) application
					.getAttribute("activeSessions");
			if (activeSessions != null) {
				activeSessions.remove(e.getSession().getId());
				application.setAttribute("activeSessions", activeSessions);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
		}
	}

}
